// API 基础路径
const API_BASE = '/api/v1';

// 知识库管理
async function createKnowledgeBase() {
    const name = document.getElementById('kb-name').value;
    const description = document.getElementById('kb-desc').value;
    const embeddingModel = document.getElementById('embedding-model').value;

    try {
        const response = await fetch(`${API_BASE}/knowledge-base`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name,
                description,
                embedding_model: embeddingModel
            })
        });

        if (response.ok) {
            loadKnowledgeBases();
            document.getElementById('kb-name').value = '';
            document.getElementById('kb-desc').value = '';
        } else {
            const error = await response.json();
            alert(error.message);
        }
    } catch (error) {
        console.error('Error:', error);
        alert('创建知识库失败');
    }
}

async function loadKnowledgeBases() {
    try {
        const response = await fetch(`${API_BASE}/knowledge-base`);
        const data = await response.json();
        
        // 更新知识库列表
        const kbList = document.getElementById('kb-list');
        kbList.innerHTML = data.data.items.map(kb => `
            <div class="border p-4 rounded">
                <h3 class="font-bold">${kb.name}</h3>
                <p class="text-gray-600">${kb.description}</p>
                <p class="text-sm text-gray-500">文档数量: ${kb.document_count}</p>
            </div>
        `).join('');

        // 更新选择框
        const kbSelects = ['kb-select', 'chat-kb-select'];
        kbSelects.forEach(id => {
            const select = document.getElementById(id);
            select.innerHTML = data.data.items.map(kb =>
                `<option value="${kb.id}">${kb.name}</option>`
            ).join('');
        });
    } catch (error) {
        console.error('Error:', error);
    }
}

// 文档管理
async function uploadDocument() {
    const kbId = document.getElementById('kb-select').value;
    const files = document.getElementById('doc-file').files;
    
    for (const file of files) {
        const formData = new FormData();
        formData.append('file', file);

        try {
            const response = await fetch(`${API_BASE}/document/upload/${kbId}`, {
                method: 'POST',
                body: formData
            });

            if (response.ok) {
                loadKnowledgeBases();  // 刷新知识库列表
            } else {
                const error = await response.json();
                alert(`上传失败: ${error.message}`);
            }
        } catch (error) {
            console.error('Error:', error);
            alert('上传文档失败');
        }
    }
    
    document.getElementById('doc-file').value = '';
}

// 对话功能
let currentController = null;

async function sendMessage() {
    const input = document.getElementById('chat-input');
    const query = input.value.trim();
    if (!query) return;

    const kbId = document.getElementById('chat-kb-select').value;
    const model = document.getElementById('chat-model').value;
    const systemPromptId = document.getElementById('system-prompt').value;
    
    // 添加用户消息
    addMessage(query, 'user');
    input.value = '';

    // 如果有正在进行的对话，先中止它
    if (currentController) {
        currentController.abort();
    }

    // 创建新的 AbortController
    currentController = new AbortController();

    try {
        const response = await fetch(`${API_BASE}/chat/${kbId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                query,
                model,
                system_prompt_id: systemPromptId || undefined
            }),
            signal: currentController.signal
        });

        const reader = response.body.getReader();
        let assistantMessage = '';

        while (true) {
            const {value, done} = await reader.read();
            if (done) break;
            
            const text = new TextDecoder().decode(value);
            assistantMessage += text;
            updateLastMessage(assistantMessage);
        }
    } catch (error) {
        if (error.name === 'AbortError') {
            console.log('Chat aborted');
        } else {
            console.error('Error:', error);
            addMessage('对话出错了，请稍后重试', 'assistant');
        }
    } finally {
        currentController = null;
    }
}

function addMessage(text, role) {
    const messages = document.getElementById('chat-messages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}-message`;
    messageDiv.textContent = text;
    messages.appendChild(messageDiv);
    messages.scrollTop = messages.scrollHeight;
}

function updateLastMessage(text) {
    const messages = document.getElementById('chat-messages');
    const lastMessage = messages.lastElementChild;
    if (lastMessage && lastMessage.classList.contains('assistant-message')) {
        lastMessage.textContent = text;
    } else {
        addMessage(text, 'assistant');
    }
}

// 刷新知识库列表
async function refreshKnowledgeBases() {
    await loadKnowledgeBases();
}

// 预览文档分段
async function previewSplit() {
    const file = document.getElementById('doc-file').files[0];
    if (!file) {
        alert('请先选择文件');
        return;
    }

    const formData = new FormData();
    formData.append('file', file);
    formData.append('method', 'char');  // 默认使用字符分割

    try {
        const response = await fetch(`${API_BASE}/document/preview`, {
            method: 'POST',
            body: formData
        });

        if (response.ok) {
            const result = await response.json();
            const preview = result.data.chunks.join('\n\n---\n\n');
            alert('文档分段预览：\n\n' + preview);
        } else {
            const error = await response.json();
            alert(`预览失败: ${error.message}`);
        }
    } catch (error) {
        console.error('Error:', error);
        alert('预览失败');
    }
}

// 停止对话
function stopChat() {
    if (currentController) {
        currentController.abort();
        addMessage('对话已停止', 'system');
    }
}

// 加载系统提示词模板
async function loadSystemPrompts() {
    try {
        const response = await fetch(`${API_BASE}/system-prompt`);
        const data = await response.json();
        
        const select = document.getElementById('system-prompt');
        select.innerHTML = `<option value="">默认系统提示词</option>` + 
            data.data.items.map(prompt =>
                `<option value="${prompt.id}">${prompt.name}</option>`
            ).join('');
    } catch (error) {
        console.error('Error:', error);
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    loadKnowledgeBases();
    loadSystemPrompts();
}); 